package com.hq.hotl.realm;

import com.hq.hotl.dao.CustomerDao;
import com.hq.hotl.pojo.Customer;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.shiro.util.ByteSource;
import java.util.HashSet;
import java.util.Set;

public class MyShiroRealm  extends AuthorizingRealm {
@Autowired
private CustomerDao customerDao;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("shiro来找我们获取授权信息拉！");
        //获取当前已认证的用户的账号
        String username =(String)principals.getPrimaryPrincipal();
        Customer customer = customerDao.queryOne(username);
        Set<String> roles = new HashSet<>();
        int state = customer.getState();
        if (state==1) {
            roles.add("管理员");
        }else roles.add("用户");
        //授权信息对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //设置角色信息
        info.setRoles(roles);
        //设置权限信息
        return info;
    }

    //获取验证信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //使用taken对象获取带登录的用户名
        String username=(String)token.getPrincipal();
        //从数据库中查到该customer信息
        Customer customer = customerDao.queryOne(username);
        //判断该用户是否存在
        if (customer==null){
            throw new UnknownAccountException(username+"不存在");
        }
        //保存查询出来的对象
        //获取shiro提供的当前用户的会话对象
        Session session = SecurityUtils.getSubject().getSession();
        //在session提供的会话对象中共享数据
        session.setAttribute("customer",customer);
        //我们创建的一个SimpleAuthenticationInfo对象
        //传三个参数，第一个参数：用户名，第二个参数：数据库中的用户密码。第三个参数：realm的名称
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(customer.getUsername(), customer.getPassword(), getName());
        return info;
    }
}
